const axios = require("axios");
const { apiHost } = require("../config");
const mysql = require('../mysql/db')
/**
 * 响应 GET 请求（响应微信配置时的签名检查请求）
 */
async function list(ctx, next) {

  const { q, page = 1, size = 20 } = ctx.request.query
  let data = []
  if (q) {
    data = await mysql('poetry').select('*')
      .where('title', 'like', `%${q}%`)
      .orWhere('content', 'like', `%${q}%`)
      .orWhere('author', 'like', `%${q}%`)
      .limit(size).offset((page - 1) * size)
  } else {
    data = await mysql('poetry').select('*')
      .limit(size).offset((page - 1) * size)
  }

  ctx.body = data.map(item => {
    item.content = item.content.split('|')
    item.yunlv_rule = item.yunlv_rule.split('|')
    return item;
  });
}

async function findById(ctx, next) {
  // 检查签名，确认是微信发出的请求
  const { id } = ctx.params;
  //const { data } = await axios.get(apiHost + "/topics/" + id);
  const data = await mysql('poetry').select('*').where({ id: parseInt(id) })
  const one = data[0]
  one.content = one.content.split('|');
  one.yunlv_rule = one.yunlv_rule.split('|');
  ctx.body = one;
}

async function save(ctx,next){
  const { poetries } = ctx.request.body;
  //const { data } = await axios.get(apiHost + "/topics/" + id);
  const data = await mysql('poetry').returning('id').insert(poetries)
  ctx.body = data;
}


module.exports = {
  findById,
  list,
  save,
};
